const request = require('request');
const Core = require('../lib/core');
const Position = require('../model/Position');

function uploadPosition(json) {
	let obj = JSON.parse(json);
	let date = (obj.addDate).replace("T", " ");
	let positionModel = {
		gps_no: obj.GPSNO,
		longitude: obj.longitude,
		latitude: obj.latitude,
		speed: obj.speed,
		direction: obj.direction,
		add_date: new Date(date).getTime() / 1000,
		protocol_no: obj.protocolNo,
		factory_code: obj.factoryCode,
		type: obj.type,
		imei: obj.IMEI,
		position: obj.position,
		is_equip: obj.isEquip,
		move_code: obj.moveCode,
		warn_code: obj.warnCode,
		iccd_code: obj.ICCDCode,
		serial_code: obj.serialCode,
		dg: obj.D_G,
		sim: obj.SIM,
		remark: obj.remark
	};

	return Position.create(positionModel)
		.then(res => {
			return null;
		})
		.catch(err => {
			console.log(err)
		});
}

function direct(gpsNo, directState, protocolNo, factoryCode, type, directCode, remark) {
	let nowStamp = parseInt(new Date(Date.now()).getTime() / 1000);

	let reqJson = {
		GPSNO: gpsNo,
		directState: directState,
		protocolNo: protocolNo,
		factoryCode: factoryCode,
		type: type,
		addDate: nowStamp,
		directCode: directCode,
		remark: remark
	};

	return new Promise(function(resolve, reject) {
		request.post({
			url: `http://47.96.231.186:8090/GPS/direct/${nowStamp}`,
			form: reqJson
		}, function (error, response, body) {
			if (!error && response.statusCode == 200) {
				resolve(body);
			} else {
				reject(error);
			}
		});
	});
}

function getPositionOfLatest(gpsNo) {
	let query = {
		gps_no: gpsNo.trim()
	};

	return Position.findOne(query)
		.sort({add_date: -1})
		.exec()
		.then(docs => {
			return docs;
		});
}

function getPositionOfPeriod(gpsNo, startTime, endTime) {
	let resultList;


	let query = {
		gps_no: Core.Util.trim(gpsNo)
	};

	if (startTime && endTime) {
		query.add_date = {
			$gte: startTime,
			$lt: endTime
		}
	} else if (startTime) {
		query.add_date = {
			$gte: startTime
		}
	} else {
		query.add_date = {
			$lt: endTime
		}
	}

	return Position.find(query)
		.sort({add_date: -1})
		.exec()
		.then(docs => {
			return Core.Util.formatModelList(docs, Position.processModel, Position.basicAttributes);
		})
		.then(list => {
			resultList = list;
			return Position.count(query);
		})
		.then(count => {
			return {
				count: count,
				list: resultList
			};
		});
}

module.exports = {
	uploadPosition: uploadPosition,
	direct: direct,
	getPositionOfLatest: getPositionOfLatest,
	getPositionOfPeriod: getPositionOfPeriod
};